import {defineStore} from 'pinia'
import {reactive} from 'vue'
import {getAllBusinessCodeFromCacheApi} from '@/api/system/businessCode.api'
import {cacheKeys} from '@/stores/constant/cacheKey'

export const useBusinessCodeStore = defineStore(cacheKeys.BUSINESS_CODE, () => {

	/**
	 * 业务编码集合
	 */
	const businessCodeCollection = reactive<BusinessCodeCollection>({})

	/**
	 * 从缓存中获取所有业务编码数据（增量更新）
	 */
	async function fetchBusinessCodes() {
		// resetBusinessCodeStore()
		const businessCodeData = (await getAllBusinessCodeFromCacheApi()).data
		for (const key in businessCodeCollection) {
			if (!Object.hasOwn(businessCodeData, key)) {
				delete businessCodeCollection[key]
			}
		}
		for (const key in businessCodeData) {
			businessCodeCollection[key] = businessCodeData[key]
		}
	}

	function resetBusinessCodeStore() {
		for (const key in businessCodeCollection) {
			delete businessCodeCollection[key]
		}
	}

	return {
		businessCodeCollection: businessCodeCollection,
		fetchBusinessCodes: fetchBusinessCodes,
		resetBusinessCodeStore: resetBusinessCodeStore
	}
}, {
	persist: {
		key: cacheKeys.BUSINESS_CODE,
		storage: window.localStorage
	}
})
